/**
 * 初始化权限树
 */
var PermissionTree = (function initPermissionTree() {

    let layer, authtree;

    let treeData;

    let init = function(layui, setting){
        layer = layui.layer;
        authtree = layui.authtree;

        $.ajax({
            type: "get",
            url: "/auth/getPermissionTree",
            success: function (res) {
                if(res.code == 0){
                    // let data = listToTreeJson(res.data);
                    // console.log('id', setting.elem.substring(1, setting.elem.length));
                    treeData = res.data;
                    if(setting && setting.success){
                        setting.success(treeData);
                    }
                }else{
                    layer.msg(res.msg, {icon: 4});
                }

            },
            error: function (res) {
                layer.msg(res.status || '发生了错误', {icon: 4});
            }
        });

    };


    let render = function(setting, checkedIds){
        let trees = authtree.listConvert(treeData, {
            primaryKey: 'id'
            ,startPid: 0
            ,parentKey: 'pid'
            ,nameKey: 'name'
            ,valueKey: 'id'
            ,checkedKey: checkedIds || []
            ,nodeTypeKey: 'istype'
        });
        // console.log('checkedIds', checkedIds);
        // console.log('trees',trees);
        authtree.render(setting.elem, trees,{
            layfilter: setting.id,
            howCheckbox: true,
            autowidth: true,
            inputname: "perms"
        });

        //格式化istype 样式
        $('#permission-tree').find('input.authtree-checkitem[nodetype]').each((index, each)=>{
            let istype = parseInt($(each).attr('nodetype'));
            let span = $(each).prev();//next().find('>span');
            if(span.length == 0){return;}
            switch (istype) {
                case 0:
                    //菜单
                    $(`<label class="type-label layui-icon layui-icon-layer"></label>`).insertAfter(span);
                    break;
                case 1:
                    //功能
                    $(`<label class="type-label layui-icon layui-icon-component"></label>`).insertAfter(span);
                    // span.append();
                    break;
            }

        })

    };


    return {
        init: init,
        render: render
    }
})();

/**
 * list转化为tree结构的json数据
 */
function listToTreeJson(data) {
    //data不能为null，且是数组
    if (data != null && (data instanceof Array)) {
        //递归转化
        var getJsonTree = function (data, parentId) {
            if(data && data.length >0){
                var itemArr = [];
                for (var i = 0; i < data.length; i++) {
                    var node = data[i];
                    if (node.pId == parentId && parentId != null) {
                        var newNode = {
                            name: node.name,
                            spread: true,
                            value: parseInt(node.id),
                            id: parseInt(node.id),
                            pid: parseInt(node.pId),
                            list: getJsonTree(data, node.id)
                        };
                        if(!newNode.list){delete newNode.list;}
                        itemArr.push(newNode);
                    }
                }
                return itemArr.length >0 ? itemArr: undefined;
            }
            // console.log('null');
        };

        return getJsonTree(data, 0);
    }
}


/**
 * tree数据转List
 * @param list
 * @return {Array}
 */
function treeData2List(list){

    let result = [];

    let parse = function (list) {
        for(let i in list){
            let each = list[i];
            let item = {};
            for(let key in each){
                item[key] = each[key];
            }
            delete item.children;
            result.push(item);
            if(each.children && each.children.length >0){
                parse(each.children);
            }

        }
    };
    parse(list);
    return result;
}